<?php
defined('IN_XLP') or die('Access Denied');
/*
 * 微信统一支付模型
 */
class weixinUnipayModel extends Model {

    public function __construct() {
        parent::__construct();
        T('weixin/weixin.unipay');
    }

    /*
     * 发起网页支付
     */
    public function callWebPay($arr=array(), $notify="") {
        try {
            
            $wx   = new weixinUnipay();

            if($notify) {
                $wx->setNotifyURL($notify);
            }

            $arr['trade_type'] = 'JSAPI';

            $p     = $wx->order($arr);
            $param = $wx->getJSAPIParam($p['prepay_id']);
            return $param;
        } catch (Exception $e) {
            $this->errorLog($e);
        }
    }

    /*
     * 发起APP支付
     */
    public function callAppPay($arr=array(), $notify="") {
        try {
            
            $wx = new weixinUnipay();

            if($notify) {
                $wx->setNotifyURL($notify);
            }

            $arr['trade_type'] = 'APP';
            $p     = $wx->order($arr);
            $param = $wx->getAppParam($p['prepay_id']);

            return $param;
        } catch (Exception $e) {
            $this->errorLog($e);
        }
    }

    /*
     * 发起原生支付
     */
    public function callNativePay($arr=array(), $notify="") {
        try {

            $wx = new weixinUnipay();

            if($notify) {
                $wx->setNotifyURL($notify);
            }

            $arr['trade_type'] = 'NATIVE';
            $p = $wx->order($arr);

            return $p['code_url'];
        } catch (Exception $e) {
            $this->errorLog($e);
        }
    }


    /*
     * 验证微信通知数据 返回相关数据
     */
    public function checkNotify() {
        try {
            $wx = new weixinUnipay();
            $data = $wx->checkNotify();
            $this->notifyLog($data);

            return $data;
        } catch (Exception $e) {
            $this->errorLog($e);   
        }
    }

    private function errorLog($exception=null) {
        if($exception) {
            $msg   = $exception->getMessage();
            $debug = $exception->getTraceAsString();
            saveLog('weixinUnipay/error', $msg.' ==> '.$debug);
            showError($msg);
        }
    }

    /*
     * 记录通知信息
     */
    private function notifyLog($data) {
        M('unipay_log')->insert(array(
            'pay_type'       => 'WX-'.$data['trade_type'],
            'out_trade_no'   => $data['out_trade_no'],
            'transaction_id' => $data['transaction_id'],
            'total_fee'      => $data['total_fee'],
            'time_end'       => $data['time_end'],
            'data_all'       => json_encode($data),
            'create_time'    => TIME,
        ));
    }
}